package com.eascs.fp.message.manager.impl;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.fp.common.dao.BaseDao;
import com.eascs.fp.common.entity.MsgTemplateEntity;
import com.eascs.fp.common.vo.MsgTemplateQueryVO;
import com.eascs.fp.message.manager.IMsgTemplateManager;

@Repository
public class MsgTemplateManagerImpl extends BaseDao implements IMsgTemplateManager {

	@Override
	public boolean add(MsgTemplateEntity entity) {
		Date date = new Date();
		entity.setCreateTime(date);
		entity.setUpdateTime(date);
		return this.insert(entity);
	}
	
	@Override
	public boolean update(MsgTemplateEntity entity) {
		
		Date date = new Date();
		entity.setUpdateTime(date);
		return this.updateById(entity);
	}


	@Override
	public MsgTemplateEntity queryById(String id) {
		return this.getById(MsgTemplateEntity.class, id);
	}

	@Override
	public MsgTemplateEntity queryByCode(String code) {
		String sql = "select * from fp_msg_template where template_code=?";
		return this.findEntity(sql, MsgTemplateEntity.class, code);
	}

	@Override
	public boolean lock(String id, boolean lock) {
		String sql = "update fp_msg_template set is_lock=? where id=?";
		return this.execute(sql, lock?0:1, id);
	}

	@Override
	public PageResult<Object[]> page(MsgTemplateQueryVO vo) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, vo.getPageSize(), vo.getShowPage());
		StringBuilder sql = new StringBuilder("select tem.id,template_code,template_name,item.item_name,case when tem.is_lock=0 then '启用' else '停用' end as is_lock from fp_msg_template tem ");
		sql.append("LEFT JOIN p2p_datadic_item item ON item.item_code = tem.template_type AND item.dd_no = 11 where 1=1 ");
		
		if (StringUtils.isNotBlank(vo.getTemplateName())) {
			
	       sql.append(" and template_name like ?");
			
		  sqlPageQuery.addParam("%" + vo.getTemplateName()+ "%");

		}
		if (StringUtils.isNotBlank(vo.getTemplateCode())) {
		
		    sql.append(" and template_code like ?");
		    sqlPageQuery.addParam("%" + vo.getTemplateCode()+ "%");
			
		}
		if (StringUtils.isNotBlank(vo.getIsLock())) {
			sql.append(" and tem.is_lock=?");
			sqlPageQuery.addParam(vo.getIsLock());
		}
		
		if (StringUtils.isNotBlank(vo.getTemplateType())) {
			sql.append(" and tem.template_type=?");
			sqlPageQuery.addParam(vo.getTemplateType());
		}
		if(StringUtils.isNotBlank(vo.getOrderby())){
			sql.append(" order by ? ");
			sqlPageQuery.addParam(vo.getOrderby());
			if(StringUtils.isNotBlank(vo.getOrder())){
				sql.append(" ? ");
				sqlPageQuery.addParam(vo.getOrder());
			}
		} else{
			sql.append(" order by create_time desc ");
		}
		sqlPageQuery.setQuerySql(sql.toString());
		
		return  this.findDataWithPage(sqlPageQuery);
	}

	
}
